<template>
  <div class="login">
    <el-form ref="loginForm" label-width="80px" label-position="right" :model="formItem" :rules="rules">
      <div class="login-logo">登录</div>
      <el-form-item prop="userName" label="用户名">
        <el-input v-model="formItem.userName" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input type="password" v-model="formItem.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item prop="captcha" label="验证码">
        <el-input v-model="formItem.captcha" placeholder="请输入验证码" style="width: calc(100% - 116px);"></el-input>
        <div class="captcha" style="width: 100px;float: right;height: 40px;">
          <img class="white-color" :src="imgCaptcha" @click="resetCaptcha">
        </div>
      </el-form-item>
      <div style="text-align: center;">
        <div>
          <el-button style="width: 75%;" size="medium" type="primary" @click.native.prevent="login">登录</el-button>
        </div>
        <nuxt-link to="/register">
          <el-button type="text">注册</el-button>
        </nuxt-link>
      </div>
    </el-form>
  </div>
</template>

<script>
import md5 from 'md5'

export default {
  data () {
    return {
      formItem: {},
      imgCaptcha: 'api/captcha'
    }
  },
  created () {
    this.rules = {
      userName: [
        { required: true, message: '请输入昵称' }
      ],
      password: [
        { required: true, message: '请输入密码' }
      ],
      captcha: [
        { required: true, message: '请输入验证码' }
      ]
    }
  },
  methods: {
    //重置验证码
    resetCaptcha () {
      this.imgCaptcha = `api/captcha?_t${new Date().getTime()}`
    },
    login () {
      this.$refs.loginForm.validate(valid => {
        if (!valid) return
        this.$axios({
          url: 'user/login',
          method: 'post',
          data: {
            ...this.formItem,
            password: md5(this.formItem.password + 'lw')
          }
        }).then(res => {
          if (res.code == -1) {
            this.resetCaptcha()
            this.$message.error(res.message)
          } else {
            const { userId, token } = res.data
            sessionStorage.setItem('userId', userId)
            sessionStorage.setItem('token', token)
            this.$router.push('/userCenter')
          }
        })
      })
    }
  }
}
</script>
<style lang="less">
html, body {
  background: #dddddd;
}
</style>
<style lang="less" scoped>
.login {
  width: 480px;
  margin: 0 auto;
  margin-top: 120px;
  background: #FFFFFF;
  border-radius: 8px;
  padding: 16px;
  padding-bottom: 24px;
  .login-logo {
    text-align: center;
    font-size: 28px;
    font-weight: bold;
    margin-bottom: 16px;
  }
  .white-color {
    background: #FFFFFF;
  }
}
</style>
